// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const rp = require('request-promise');

const weatherKey = 'd0473e36eae24b2db497acc7c677b8d6';

const baseUrl = `https://free-api.heweather.net/s6/weather`


cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  // 实况天气信息
  app.router('getNowWeather', async (ctx, next) => {
    const res = await rp(`${baseUrl}/now?location=${event.lon},${event.lat}&key=${weatherKey}`).then(res => {
      return res;
    })
    ctx.body = res;
    console.log(res)
  })
  // 3-10天预报
  app.router('getForecastWeather', async (ctx,next) => {
    const res = await rp(`${baseUrl}/forecast?location=${event.lat},${event.lon}&key=${weatherKey}`).then(res => {
      return res;
    })
    ctx.body = res;
    console.log(res)
  })
  // 空气质量
  app.router('getAirWeather', async (ctx, next) => {
    const res = await rp(`https://free-api.heweather.net/s6/air/now?location=${event.lat},${event.lon}&key=${weatherKey}`).then(res => {
      return res;
    })
    ctx.body = res;
    console.log(res)
  })
  // 小时
  app.router('getHourlyWeather', async (ctx, next) => {
    const res = await rp(`${baseUrl}/hourly?location=${event.lat},${event.lon}&key=${weatherKey}`).then(res => {
      return res;
    })
    ctx.body = res;
    console.log(res)
  })
  // 生活指数
  app.router('getLifeStyleWeather', async (ctx, next) => {
    const res = await rp(`${baseUrl}/lifestyle?location=${event.lat},${event.lon}&key=${weatherKey}`).then(res => {
      return res;
    })
    ctx.body = res;
    console.log(res)
  })
  return app.serve()
}